package com.happy.mycar;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.ExistingWorkPolicy;
import androidx.work.ForegroundInfo;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class MyBLEWorker extends Worker {

    public static void doWorke(Context context) {
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyBLEWorker.class).build();
        //区分debug和release版本
        if (false) {
            // 如果是debug版本，重启任务
            WorkManager.getInstance(context).enqueueUniqueWork("MyCarWork_2025",
                    ExistingWorkPolicy.REPLACE, // 如果已存在，则替换现有任务
                    workRequest);
        } else {
            // 如果是release版本，保留现有任务
            WorkManager.getInstance(context).enqueueUniqueWork("MyCarWork_2025",
                    ExistingWorkPolicy.KEEP, // 如果已存在，则保留现有任务
                    workRequest);
        }
    }

    public MyBLEWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        MyBLEService.createNotificationChannel(getApplicationContext());
        CBLEDevice.getInstance().setContext(getApplicationContext());
    }

    ForegroundInfo createForegroundInfo() {
        return new ForegroundInfo(1, createNotification("后台任务运行中...").build());
    }
    private NotificationCompat.Builder createNotification(String content) {
        Intent intent = new Intent(this.getApplicationContext(), MainActivity.class);
        // 如果希望在应用已在后台运行时，将其带到前台并清除之前的活动栈，可以添加以下标志
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 创建通知
        return new NotificationCompat.Builder(this.getApplicationContext(), "channel_id")
                .setContentTitle("智能车钥匙")
                .setContentText(content)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH);
    }
    //更新通知
    public void updateNotification(String content) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "channel_id")
                .setContentTitle("智能车钥匙")
                .setContentText(content)
                .setSmallIcon(R.drawable.ic_launcher_foreground);
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(1, builder.build());
        }
    }

    @NonNull
    @Override
    public Result doWork() {
        //使用setForegroundAsync把它设置为前台任务
        setForegroundAsync(createForegroundInfo());
        // 在这里实现你的后台任务逻辑
        CBLEDevice.getInstance().registerReceiver();
        while (true) {
            try {
                if (CBLEDevice.getInstance().isConnected()) {
                    System.out.println("蓝牙已连接...");
                    Thread.sleep(3000);
                } else {
                    System.out.println("蓝牙未连接，尝试连接...");
                    CBLEDevice.getInstance().connectToBLEDevice("MyCar");
                    Thread.sleep(300);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
        CBLEDevice.getInstance().unregisterReceiver();
        return Result.success();
    }
}